<?php
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/daos/UsersDAO.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/models/interfaces/IUser.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/views/GeneralView.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/controlers/interfaces/IController.php');

/**
 * @access public
 * @author Edgar Morán
 * @package Aplicación.controlers
 */
class UsersController implements IController {
	/**
	 * @AssociationType Aplicación.daos.UsersDAO
	 * @AssociationKind Composition
	 */
	private $_usersDAO;
	/**
	 * @AssociationType Aplicación.models.interfaces.IUser
	 * @AssociationKind Composition
	 */
	public $_iUser;
	/**
	 * @AssociationType Aplicación.views.GeneralView
	 * @AssociationKind Composition
	 */
	public $_generalView;
	
	public $_actionErrors;

	
	public function __construct() {
		$_usersDAO= new UsersDAO();
		$_iUser= NULL;
		$_actionErrors =NULL;
		//$generalView= new GeneralView();	
	}
	private function  validateAddUser($params){
		//se debe tener en cuenta la diferencia entre validar y verificar
		$errors=NULL;
		$validState=true;
		$valid = new Validations();
		$valid->validVariable('userName',$params['userName'], true , 'string', 3, 200);
		$valid->validVariable('name',$params['name'], true,'string', 3, 200);
		$valid->validVariable('lastName',$params['lastName'], true, 'string', 3, 200);
		$valid->validVariable('email',$params['email'], true, 'email', 10, 200);
		$valid->validVariable('userType',$params['userType'], true, 'enum', 1, 1, NULL, NULL, array(1,2));
		$valid->validVariable('password',$params['password'], true, 'string', 6, NULL);
		$valid->validVariable('passwordRepeat',$params['passwordRepeat'], true, 'string', 6, NULL);
		
		if ($valid->hasError()){
			//print_r($valid->getErrors());
			$errors=$valid->getErrors();
			$validState=false; 
		}
		
		$this->_usersDAO= new UsersDAO();
		//echo "si";	
		if($this->_usersDAO->existUserEmail($params['email'])){
			//echo "si";
			$errors['email']=str_replace('$', $params['email'], ERRORAddUserExistUserEmail) ;
			//$errors['email']=
			$this->_actionErrors=$errors;
			$validState=false;
		}
		if($this->_usersDAO->existUserName($params['userName'])){
			$errors['userName']=str_replace('$', $params['userName'], ERRORAddUserExistUserName) ;
			$this->_actionErrors=$errors;
			$validState=false;
		}
		if(!($params['password']==$params['passwordRepeat'])){
			$errors['password']=ERRORAddUserDiferentPassword;
			
			$this->_actionErrors=$errors;
			$validState=false;
		}
		$this->_actionErrors=$errors;	
			//verificar
			//se debe vericar en la base de datos que el userName y el email NO existan
			
		return $validState;
	}
	
	
	/**
	 * @access public
	 * 
	 * @ReturnType void
	 */

	public function addUser() {
		
		$fc = FrontController::getInstance();
    	$params = $fc->getParams();// Not yet implemented
		$view = new View(TPLaddUser);
		$util = new Validations();
		$successMessage= NULL;
		
		$view->tpl->pageTitle="Agregar Usuario";
		$view->tpl->actionTitle="Agregar usuario";
		$view->tpl->actionError=false;

		$params['userTypes']= array(
			array(
		      "value" => '',
		      "name" => 'Seleccione el tipo de Usuario',
		      "selected" => true
		    ),
		    array(
		      "value" => '1',
		      "name" => 'Admnistrador',
		      "selected" => false
		    ),
		    array(
		      "value" => '2',
		      "name" => 'Vendedor',
		      "selected" => false
		    ),
		);
		//$params['userIdType']="ActorUser"; 
			
		//si se va a agregar un usuario
    	if(!empty($params['submit'])){

			//si los datos son validos
			if ($this->validateAddUser($params)){
				$params['access']='t';
				$this->_usersDAO= new UsersDAO();
				$this->_iUser = new ActorUser($params);
				
				if($this->_usersDAO->addUser($this->_iUser)){
					setCookieLive ("MensajeExito", str_replace('$', $params['userName'], SUCCESSAddUser) , time()+3600);
					//echo "si";
					header('Location:'.ADDUSER);
				}
				else {
					$view->tpl->actionError=ERRORDB;
				}

			}
			else{
				//$params['userTypes'][0]['value']='x';
				//$params['userTypes'][1]['value']='y';
				//$params['userType']='x';
				$seletecValue=$util->array_search_key($params['userType'],$params['userTypes']);

				
				if(!empty($seletecValue)){
					$params['userTypes'][0]['selected']=false;
					$params['userTypes'][$seletecValue]['selected']=true;
				}
				$view->tpl->actionError=ERRORGeneral;
				$view->tpl->actionErrors=$this->_actionErrors;

			}
			
			
		}
		else{
			if(isset($_COOKIE['MensajeExito']))
				$successMessage=$_COOKIE['MensajeExito'];
			removeCookieLive('MensajeExito');
		}

		$view->tpl->params=$params;
		$view->tpl->successMessage=$successMessage;
		$result = $view->render();    
		$fc->setBody($result);
		
	}

	/**
	 * @access public
	 * @param int aId
	 * @return boolean
	 * @ParamType aId int
	 * @ReturnType boolean
	 */
	public function desactiveUser($id) {
		// Not yet implemented
	}

	/**
	 * @access public
	 * @param int aId
	 * @return Aplicación.models.interfaces.IUser
	 * @ParamType aId int
	 * @ReturnType Aplicación.models.interfaces.IUser
	 */
	public function getUser($aId) {
		// Not yet implemented
	}

	/**
	 * @access public
	 * @param int aId
	 * @return void
	 * @ParamType aId int
	 * @ReturnType void
	 */
	public function viewUser() {
		$fc = FrontController::getInstance();
    	$params = $fc->getParams();
		
    	$view = new View(TPLviewUser);

		$view->tpl->pageTitle="Listar Usuarios";
		$view->tpl->actionTitle="Ver Usuario: $";
		
		$this->_usersDAO= new UsersDAO();
		
		if (!empty($params['id']) && $this->_usersDAO->existUser($params['id'])){
			$view->tpl->existUser=true;
			$user=$this->_usersDAO->getUser($params['id']);
			$view->tpl->user=$user;
			print_r($user);
		}
		$result = $view->render();    
		$fc->setBody($result);
	}

	/**
	 * @access public
	 * @return array
	 * @ReturnType array
	 */
	public function getUsers() {
		// Not yet implemented
	}

	/**
	 * @access public
	 * @return void
	 * @ReturnType void
	 */
	public function listUsers() {
		// Not yet implemented
		
				
		$fc = FrontController::getInstance();
    	$params = $fc->getParams();// Not yet implemented
		$view = new View(TPLlistUsers);
		$view->tpl->hasItems=false;
		
		$view->tpl->pageTitle="Listar Usuarios";
		$view->tpl->actionTitle="Listado de Usuarios";
			
		$this->_usersDAO= new UsersDAO();
		
		if ($this->_usersDAO->howManyUsers()){
			$view->tpl->hasItems=true;
			$users=$this->_usersDAO->getUsers();
			$needle=array( array ('key'=>'userType', 'search'=> '1', 'replace'=>'Administrador'),
							array ('key'=>'userType', 'search'=> '2', 'replace'=>'Vendedor') );
			//arra
			//arrayReplace($search, $array)
			
			$users=arrayReplace($needle, $users);
			$view->tpl->users=$users;
			
		}
		$result = $view->render();    
		$fc->setBody($result);
	}

	/**
	 * @access public
	 * @param int aId
	 * @return boolean
	 * @ParamType aId int
	 * @ReturnType boolean
	 */
	public function activeUser($aId) {
		// Not yet implemented
	}

	/**
	 * @access public
	 * @param string aSearchString
	 * @return array
	 * @ParamType aSearchString string
	 * @ReturnType array
	 */
	public function searchUsers($aSearchString) {
		// Not yet implemented
	}

	/**
	 * @access public
	 * @param string aNewPassword
	 * @param string aRepeatNewPassword
	 * @ParamType aNewPassword string
	 * @ParamType aRepeatNewPassword string
	 */
	public function changePassword($aNewPassword, $aRepeatNewPassword) {
		// Not yet implemented
	}

	/**
	 * @access public
	 * @param string aState
	 * @ParamType aState string
	 */
	public function changeAccess($aState) {
		// Not yet implemented
	}
	public function modifyUser($userId){
		
	}
}
?>